/**
 * description:
 *  收费产品底部统一客服组件
 *
 * usage:
 *
 *  1. 先引用反馈助手
 *  <link rel="stylesheet" href="https://s.thsi.cn/cb?js/m/ozone/help/css/;iosSelect_v4.css;com_v4.css">
 *  <script src="https://s.thsi.cn/js/m/ozone/help/js/helper_v4.js"></script>
 *  <script src="https://s.thsi.cn/cb?js/m/ozone/help/js/;encrypt.min.js;iosSelect.js"></script>
 *  引用该组件
 *  <script src="https://s.thsi.cn/js/m/ozone/help/js/helperForProd.js"></script>
 *
 *  2. html 中添加组件根节点
 *  <div id="helperForProd"></div>
 *
 *  3. 调用组件初始化
 *  new HelperForProd({
 *    el: '#helperForProd', // 组件根节点（必填）
 *    stat: { // 埋点数据（必填）
 *      pageId: '',
 *      ext: {
 *        url_ver: ''
 *      }
 *    },
 *    sid: '207', // 产品sid（不写则默认通过遍历 prodsMap 中的 url 判断）
 *    comefrom: '', // 语音助手问句id（默认为空不显示客服助手）
 *    themeMode: getCssStyle(), // 白天/夜间模式（默认为 白天）
 *    themeVersion: 2, // 主题颜色版本号（默认为1, 最新为2）
 *    cssUnit: 'px', // css 单位（默认为 rem）
 *    extension: [{ // 扩展项（会显示在客户服务中心上面）
 *      id: 'fsp-cpsm',
 *      title: '产品说明',
 *      callback(){}
 *    }]
 *  })
 */

if (window.HelperForProd != null) {
  throw new Error('HelperForProd 全局变量已存在');
}
window._thsclog &&
  window._thsclog({
    name: 'thsc-m-helpForProd',
    ver: 'v1.0.0',
  });
const HelperForProd = function (options) {
  // 收费产品数据映射表
  const prodsMap = {
    471: {
      name: '财富密码',
      isRecommended: false,
      url: ['/wealth_key/'],
    },
    443: {
      name: '决策助手',
      isRecommended: false,
      url: ['/juece-helper/'],
    },
    207: {
      // level2
      name: 'level2', // 产品名称 用于意见反馈分类
      isRecommended: false,
      url: ['/level2/'], // 产品功能页地址中相对唯一的能起到标识该产品的一段
    },
    379: {
      // 形态掘金
      name: 'shapeExcavate',
      isRecommended: false,
      url: ['/shapeExcavate/'],
    },
    157: {
      // vip
      name: 'vip',
      isRecommended: false,
      url: ['/vip_v2/'],
    },
    115: {
      // 神奇电波
      name: 'magicWave',
      isRecommended: true,
      url: ['/magicWave_v2/', '/setDianboType'],
    },
    270: {
      // 涨价概念
      name: 'priceConcept',
      isRecommended: false,
      url: ['/priceConcept/'],
    },
    196: {
      // 手机短线宝
      name: 'mobileshortmessage',
      isRecommended: true,
      url: ['/mobileshortmessage_v2/', '/mobileshortmessage/'],
    },
    329: {
      // 黄金十分钟
      name: 'goldTenMinute',
      isRecommended: true,
      url: ['/goldTenMinute/'],
    },
    327: {
      // 主力密码
      name: 'mainForceDecode',
      isRecommended: false,
      url: ['/mainForceDecode/'],
    },
    297: {
      // ai 分时顶底
      name: 'aicnn',
      isRecommended: false,
      url: ['/aicnn/'],
    },
    280: {
      // ai 机构探测器
      name: 'mechanismDetector',
      isRecommended: false,
      url: ['/mechanismDetector/'],
    },
    304: {
      // 大盘早知道
      name: 'marketTrend',
      isRecommended: false,
      url: ['/marketTrend/'],
    },
    328: {
      // 热点擒龙
      name: 'catchDragon',
      isRecommended: false,
      url: ['/hotSpotApi/'],
    },
    335: {
      // ai 价值回归
      name: 'aiValueRegression',
      isRecommended: true,
      url: ['/aiValueRegression/'],
    },
    163: {
      // 手财经典
      name: 'mobilecfxf',
      isRecommended: true,
      url: ['/mobilecfxf/'],
    },
    193: {
      // 手财至尊
      name: 'mobilecfxfzz',
      isRecommended: true,
      url: ['/mobilecfxf/prime/v2'],
    },
    326: {
      // 龙头寻宝
      name: 'leadingTreasure',
      isRecommended: false,
      url: ['/leadingTreasure/', '/ltxbCache/'],
    },
    177: {
      // 荐股师
      name: 'mobileznfxs',
      isRecommended: true,
      url: ['/mobileznfxs/'],
    },
    269: {
      // 涨停助手
      name: 'limitUp',
      isRecommended: false,
      url: ['/limitUp/'],
    },
    251: {
      // 波段股王
      name: 'shortreco',
      isRecommended: true,
      url: ['/shortreco/'],
    },
    323: {
      // ai 波段雷达
      name: 'aiBandRadar',
      isRecommended: false,
      url: ['/aiBandRadar/'],
    },
    351: {
      // 早盘选股宝
      name: 'earlyStockPicking',
      isRecommended: true,
      url: ['/earlyStockPicking/'],
    },
    301: {
      // 避险宝
      name: 'avoidRiskUtil',
      isRecommended: false,
      url: ['/avoidRiskUtil/'],
    },
    231: {
      // 云参数
      name: 'cloudParameter',
      isRecommended: true,
      url: ['/cloudParameter/'],
    },
    171: {
      // 高级诊股
      name: 'diagnosestock',
      isRecommended: true,
      url: ['/diagnosestock/'],
    },
  };
  this.$options = options;
  this.$prod = this.getCurrentProd(prodsMap);
  if (!this.$prod) {
    throw new Error('[HelperForProd] 未匹配到当前产品信息');
  }
  this.$el = this.getElement(options.el);
  if (this.$el) {
    this.init();
  }
};
HelperForProd.prototype = {
  init() {
    // 插入 css 样式
    document.querySelector('head').appendChild(this.createStyle());
    // 插入 html
    this.$el.appendChild(this.createHTML());
    // 注册事件绑定
    this.registerEventListener();
  },
  registerEventListener() {
    const that = this;
    const helpDom = document.querySelector('.hfp-item-help');
    const callDom = document.querySelector('.hfp-item-call');
    const personDom = document.querySelector('.hfp-item-person');
    const feedbackDom = document.querySelector('.hfp-feedback-btn');
    helpDom &&
      helpDom.addEventListener('click', function () {
        that.invokeHelper(1, that.$options.stat, that.$options.comefrom, that.$options.cssUnit);
      });
    callDom &&
      callDom.addEventListener('click', function () {
        that.invokeHelper(2, that.$options.stat, that.$options.comefrom, that.$options.cssUnit);
      });
    personDom &&
      personDom.addEventListener('click', function () {
        that.invokeHelper(3, that.$options.stat, that.$options.comefrom, that.$options.cssUnit);
      });
    feedbackDom &&
      feedbackDom.addEventListener('click', function () {
        window.hxmJumpPageStat(
          `${that.$options.stat.pageId}.yjfk`,
          'free_help_feedback',
          that.$options.stat.ext
        );
        const ptcl = location.protocol;
        let feedbackPageUrl = `${ptcl}//eq.10jqka.com.cn/download/helpAndFeedback/feedback.html`;
        if (that.$prod) {
          feedbackPageUrl = `${feedbackPageUrl}?fromProductType=${that.$prod.name}`;
        }
        if (window.getAppVersion && window.getAppVersion()) {
          window.location.href = `client://client.html?action=ymtz^webid=2804^mode=new^url=${feedbackPageUrl}`;
        } else {
          window.location.href = feedbackPageUrl;
        }
      });
    if (this.$options.extension) {
      for (let i = 0; i < this.$options.extension.length; i++) {
        const extItem = this.$options.extension[i];
        if (extItem.id && extItem.callback) {
          (function (extItem) {
            const extItemDom = document.querySelector(`#${extItem.id}`);
            extItemDom &&
              extItemDom.addEventListener('click', function () {
                typeof extItem.callback === 'function' && extItem.callback();
              });
          })(extItem);
        }
      }
    }
  },
  createHTML() {
    const wrapperDiv = document.createElement('div');
    let wrapperClassName = 'helper-for-prod';
    // 黑夜模式
    if (this.$options.themeMode === 'black') {
      wrapperClassName += ' hfp-theme-dark';
      if (/Android/gi.test(navigator.userAgent)) {
        wrapperClassName += ' hfp-theme-dark-gphone';
      }
    }
    // 低版本安卓隐藏 box-shadow
    const gphoneVersion = this.getGphoneVersion();
    if (gphoneVersion && gphoneVersion.split('.')[0] < 6) {
      wrapperClassName += ' hfp-gphone-low';
    }
    wrapperDiv.setAttribute('class', wrapperClassName);
    let helperHTML = `\
    <div class="hfp-box">\
      <h2>客服中心</h2>\
      <ul>${
  this.$options.comefrom
    ? '<li class="hfp-item hfp-item-help">\
          <div>\
            <img src="//s.thsi.cn/js/m/ozone/help/images/help.png">\
            <p class="hfp-sub-txt">智能客服</p>\
          </div>\
          <div class="hfp-desc-txt">例：如何查看购买的收费产品?</div>\
        </li>'
    : ''
}<li class="hfp-item hfp-item-call">\
          <div>\
            <img src="//s.thsi.cn/js/m/ozone/help/images/call.png">\
            <p class="hfp-sub-txt">立即致电客服</p>\
          </div>\
          <div id="hfpWaitNum" class="hfp-desc-txt">如遇繁忙占线请稍后拨打</div>\
        </li>\
        <li class="hfp-item hfp-item-person">\
          <div>\
            <img src="//s.thsi.cn/js/m/ozone/help/images/person.png">\
            <p class="hfp-sub-txt">预约通话</p>\
          </div>\
          <div class="hfp-desc-txt">请在预约时段内保持电话畅通</div>\
        </li>\
      </ul>\
    </div>\
    <div class="hfp-risk-tips">\
      <span class="hfp-bold">风险提示</span><span>：\
        ${
  this.$prod && this.$prod.isRecommended
    ? '本产品所有股票池收益走势，均不代表真实收益或对未来收益之预期，计算未纳入印花税、交易费用、分红等因素的计算；所荐个股盈亏仅作统计参考之用，不建议投资者逐一操作，或作为直接投资之依据；股市有风险，投资需谨慎，同花顺云软件有限公司免责声明。'
    : '本产品不涉及投资咨询及投资顾问服务，所展示信息不构成投资建议；数据基于历史，不代表未来趋势；每个指标都有局限性，适合不同情况下的市场，请理性投资，控制风险。'
}</span>\
      <br>\
      <span class="hfp-bold">\
      ${
  this.$prod && this.$prod.isRecommended ? '证券咨询服务提供' : '产品提供'
}</span><span>：浙江同花顺云软件有限公司[编号:zx0050]</span>\
    </div>\
    <div class="hfp-feedback"><span class="hfp-feedback-btn">意见反馈</span></div>`;
    if (this.$options.extension) {
      let extensionHTML = '<div class="hfp-ext"><ul>';
      for (let i = 0; i < this.$options.extension.length; i++) {
        const extItem = this.$options.extension[i];
        if (extItem.id && extItem.title) {
          extensionHTML += `\
          <li id="${extItem.id}">\
            <div class="hfp-ext-title">${extItem.title || '标题'}</div>\
            <div class="hfp-icon-arrow"></div>\
          </li>`;
        } else {
          throw new Error('[HelperForProd] extension 缺少 id 或 title');
        }
      }
      extensionHTML += '</ul></div>';
      helperHTML = extensionHTML + helperHTML;
    }
    wrapperDiv.innerHTML = helperHTML;
    return wrapperDiv;
  },
  createStyle() {
    const that = this;
    function unitParser(val) {
      if (that.$options.cssUnit === 'px') {
        return `${val * 50}px`;
      } else {
        return `${val}rem`;
      }
    }
    const colorPlate = {
      v1: {
        light: {
          bodyBackground: '#f5f5f5',
          cardBackground: '#ffffff',
          shadow: '#eeeeee',
        },
        dark: {
          bodyBackground_iphone: '#202022',
          bodyBackground_gphone: '#171616',
          cardBackground_iphone: '#252528',
          cardBackground_gphone: '#1E1E1E',
          shadow: '#202022',
        },
      },
      v2: {
        light: {
          bodyBackground: '#f5f5f5',
          cardBackground: '#ffffff',
          shadow: '#ededed',
        },
        dark: {
          bodyBackground_iphone: '#020202',
          bodyBackground_gphone: '#171616',
          cardBackground_iphone: '#121212',
          cardBackground_gphone: '#1E1E1E',
          shadow: '#0e0e0e',
        },
      },
    };
    const color = colorPlate[`v${this.$options.themeVersion}`] || colorPlate.v1;
    if (document.querySelector('head')) {
      const styleEl = document.createElement('style');
      styleEl.innerHTML = `\
      .helper-for-prod {\
        width: 100%;\
        background-color: ${color.light.bodyBackground};\
        color: rgba(0,0,0,0.84);\
        padding-top: ${unitParser(0.2)};\
      }\
      .hfp-theme-dark {\
        background-color: ${color.dark.bodyBackground_iphone};\
        color: #D2D2D3;\
      }\
      .hfp-theme-dark-gphone {\
        background-color: ${color.dark.bodyBackground_gphone};\
      }\
      .hfp-box {\
        background-color: ${color.light.cardBackground};\
        padding: ${unitParser(0.38)} ${unitParser(0.32)} ${unitParser(0.46)};\
      }\
      .hfp-theme-dark .hfp-box {\
        background-color: ${color.dark.cardBackground_iphone};\
      }\
      .hfp-theme-dark-gphone .hfp-box {\
        background-color: ${color.dark.cardBackground_gphone};\
      }\
      .helper-for-prod .hfp-box h2 {\
        font-weight: bold;\
        font-size: ${unitParser(0.34)};\
        line-height: ${unitParser(0.36)};\
        color: rgba(0,0,0,0.84);\
      }\
      .hfp-theme-dark .hfp-box h2 {\
        color: #D2D2D3;\
      }\
      .helper-for-prod .hfp-box ul {\
        padding: 0 ${unitParser(0.24)};\
        margin-top: ${unitParser(0.3)};\
        -webkit-box-shadow: 0 0 ${unitParser(0.08)} 0 ${color.light.shadow};\
        box-shadow: 0 0 ${unitParser(0.08)} 0 ${color.light.shadow};\
        border: 1px solid ${color.light.shadow};\
        border-radius: ${unitParser(0.04)};\
      }\
      .hfp-theme-dark .hfp-box ul {\
        -webkit-box-shadow: 0 0 ${unitParser(0.08)} 0 ${color.dark.shadow};\
        box-shadow: 0 0 ${unitParser(0.08)} 0 ${color.dark.shadow};\
        border: 1px solid ${color.dark.shadow};\
      }\
      .hfp-gphone-low .hfp-box ul {\
        -webkit-box-shadow: none;\
        box-shadow: none;\
      }\
      .helper-for-prod .hfp-box li {\
        display: -webkit-box;\
        display: -webkit-flex;\
        display: -ms-flexbox;\
        display: flex;\
        -webkit-box-pack: justify;\
        -webkit-justify-content: space-between;\
        -ms-flex-pack: justify;\
        justify-content: space-between;\
        -webkit-box-align: center;\
        -webkit-align-items: center;\
        -ms-flex-align: center;\
        align-items: center;\
        height: ${unitParser(0.9)};\
      }\
      .helper-for-prod li:not(:first-child) {\
        border-top: 1px solid #eee;\
      }\
      .hfp-theme-dark li:not(:first-child) {\
        border-top: 1px solid #313131;\
      }\
      .helper-for-prod .hfp-box li div {\
        display: -webkit-box;\
        display: -webkit-flex;\
        display: -ms-flexbox;\
        display: flex;\
        -webkit-box-align: center;\
        -webkit-align-items: center;\
        -ms-flex-align: center;\
        align-items: center;\
      }\
      .helper-for-prod .hfp-box li img {\
        width: ${unitParser(0.48)};\
        height: ${unitParser(0.48)};\
      }\
      .hfp-sub-txt {\
        font-size: ${unitParser(0.28)};\
        color: #666;\
        margin-left: ${unitParser(0.16)};\
      }\
      .hfp-theme-dark .hfp-sub-txt {\
        color: #A9A9A9;\
      }\
      .hfp-desc-txt {\
        font-size: ${unitParser(0.24)};\
        color: #999;\
      }\
      .hfp-theme-dark .hfp-desc-txt {\
        color: #8E8E8E;\
      }\
      .hfp-bold {\
        font-weight: bold;\
      }\
      .hfp-risk-tips {\
        color: #999;\
        font-size: ${unitParser(0.24)};\
        line-height: ${unitParser(0.36)};\
        padding: ${unitParser(0.4)} ${unitParser(0.32)} ${unitParser(0.46)};\
      }\
      .hfp-theme-dark .hfp-risk-tips {\
        color: #8E8E8E;\
      }\
      .hfp-feedback {\
        display: -webkit-box;\
        display: -webkit-flex;\
        display: -ms-flexbox;\
        display: flex;\
        -webkit-box-pack: center;\
        -webkit-justify-content: center;\
        -ms-flex-pack: center;\
        justify-content: center;\
        color: #4691ee;\
        font-size: ${unitParser(0.28)};\
        padding-bottom: ${unitParser(0.5)};\
      }\
      .hfp-theme-dark .hfp-feedback {\
        color: #3D76B8;\
      }\
      [data-adapter="thsIphoneXAdapter"] .hfp-feedback {\
        padding-bottom: ${unitParser(1.08)};\
      }\
      .hfp-icon-arrow {\
        background: url() no-repeat;\
        background-size: contain;\
        width: ${unitParser(0.2)};\
        height: ${unitParser(0.12)};\
        -webkit-transform: rotate(-90deg);\
        transform: rotate(-90deg);\
      }\
      .hfp-theme-dark .hfp-icon-arrow {\
        background: url() no-repeat;\
        background-size: contain;\
      }\
      .hfp-ext {\
        margin-bottom: ${unitParser(0.2)};\
        padding: 0 ${unitParser(0.32)};\
        font-size: ${unitParser(0.32)};\
        background-color: ${color.light.cardBackground};\
      }\
      .hfp-theme-dark .hfp-ext {\
        background-color: ${color.dark.cardBackground_iphone};\
      }\
      .hfp-theme-dark-gphone .hfp-ext {\
        background-color: ${color.dark.cardBackground_gphone};\
      }\
      .hfp-ext li {\
        height: ${unitParser(0.96)};\
        display: -webkit-box;\
        display: -webkit-flex;\
        display: -ms-flexbox;\
        display: flex;\
        -webkit-box-align: center;\
        -webkit-align-items: center;\
        -ms-flex-align: center;\
        align-items: center;\
        -webkit-box-pack: justify;\
        -webkit-justify-content: space-between;\
        -ms-flex-pack: justify;\
        justify-content: space-between;\
      }`;
      return styleEl;
    }
  },
  // 调用反馈助手
  invokeHelper(autoTrigger, stat, comefrom, cssUnit) {
    window.Helper &&
      window.Helper({
        autoTrigger,
        pageId: stat.pageId,
        url_ver: stat.ext.url_ver,
        comefrom,
        cssUnit: cssUnit || 'rem',
        handleWaitNum(num) {
          if (num >= 1) {
            document.querySelector('#hfpWaitNum').innerHTML = `当前有${num}名用户正在排队`;
          } else {
            document.querySelector('#hfpWaitNum').innerHTML = '当前无用户排队通话';
          }
        },
      });
  },
  // 获取元素节点
  getElement(el) {
    return typeof el === 'string' ? document.querySelector(el) : el;
  },
  // 获取安卓系统版本号
  getGphoneVersion() {
    const ua = navigator.userAgent.toLowerCase();
    let version = null;
    if (ua.indexOf('android') > 0) {
      const reg = /android [\d._]+/gi;
      const v_info = ua.match(reg);
      version = `${v_info}`.replace(/[^0-9|_.]/gi, '').replace(/_/gi, '.');
    }
    return version;
  },
  /**
   * 获取当前收费产品数据
   * @param {any} prodsMap 收费产品数据表
   */
  getCurrentProd(prodsMap) {
    let currentProd = null;
    if (this.$options && this.$options.sid) {
      currentProd = prodsMap[this.$options.sid];
      return currentProd;
    }
    const currentHref = location.href;
    for (const k in prodsMap) {
      if (currentProd) {
        break;
      }
      const urls = prodsMap[k].url;
      for (let j = 0; j < urls.length; j++) {
        if (new RegExp(urls[j], 'i').test(currentHref)) {
          currentProd = prodsMap[k];
          break;
        }
      }
    }
    return currentProd;
  },
};

window.HelperForProd = HelperForProd;
